package com.smec.moblie.util;

import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;


public class WebServiceUtil {

    /**
     * 调用webservice
     *
     * @param wsdl
     * @param nameSpace      命名空间
     * @param paramName      webservice operation方法名
     * @param propertyNames  输入参数名
     * @param propertyValues 输入参数值
     * @param tag            输入参数标签
     * @return
     */
    public static String callWebservice(String wsdl, String nameSpace,
                                        String paramName, String[] propertyNames, String[] propertyValues,
                                        String tag) throws IOException, XmlPullParserException {
        String ret = null;

        // 第2步：设置WebService方法的参数
        SoapObject valueObject = new SoapObject(nameSpace, paramName);
        for (int i = 0; i < propertyValues.length; i++) {
            // tip: 根据接口情况添加标签
            if (tag != null) {
                valueObject.addProperty(tag + ":" + propertyNames[i],
                        propertyValues[i]);
            } else {
                valueObject.addProperty(propertyNames[i], propertyValues[i]);
            }

        }
        // 第3步：创建SoapSerializationEnvelope对象，并指定WebService的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);

        // 设置bodyOut属性
        ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
        headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
        envelope.bodyOut = valueObject;
        envelope.setOutputSoapObject(valueObject);
        // 第4步：创建HttpTransportSE对象，并指定WSDL文档的URL
        HttpTransportSE ht = new HttpTransportSE(wsdl, 60000);
        ht.call(null, envelope, headerPropertyArrayList);
        Object bodyIn = envelope.bodyIn;

        if (bodyIn instanceof SoapPrimitive) {
            SoapPrimitive sp = (SoapPrimitive) envelope.bodyIn;
            ret = sp.toString();
        } else if (bodyIn instanceof SoapObject) {
            SoapObject sp = (SoapObject) envelope.bodyIn;
            ret = sp.toString();
        } else {
            ret = bodyIn.toString();
        }
        return ret;
    }
}
